<template>
  <div class="upload-list-container">
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <h2>YY云盘</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-icon><User /></el-icon>
              {{ userStore.userInfo?.nickname || '用户' }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="150px" class="sidebar">
          <el-menu
            :default-active="$route.path"
            router
            background-color="#f5f5f5"
            text-color="#333"
            active-text-color="#409eff"
          >
            <el-menu-item index="/files">
              <el-icon><Folder /></el-icon>
              <span>我的文件</span>
            </el-menu-item>
            <el-menu-item index="/uploads">
              <el-icon><Upload /></el-icon>
              <span>上传列表</span>
            </el-menu-item>
            <el-menu-item index="/share">
              <el-icon><Share /></el-icon>
              <span>我的分享</span>
            </el-menu-item>
            <el-menu-item index="/recycle">
              <el-icon><Delete /></el-icon>
              <span>回收站</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-main class="main-content">

          <!-- 总进度条 -->
          <el-card v-if="uploadStore.tasks.length > 0" class="progress-card">
            <div class="total-progress-info">
              <div class="progress-text">
                <span class="progress-title">总体进度</span>
                <span class="progress-percentage">{{ uploadStore.totalProgress }}%</span>
              </div>
              <el-progress
                :percentage="uploadStore.totalProgress"
                :status="uploadStore.isUploading ? undefined : 'success'"
                :stroke-width="12"
                :show-text="false"
              />
            </div>
          </el-card>

          <!-- 统计卡片 -->
          <div class="stats-cards">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon uploading">
                  <el-icon><Loading /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ uploadStore.uploadingTasks.length }}</div>
                  <div class="stat-label">正在上传</div>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon waiting">
                  <el-icon><Clock /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ waitingTasksCount }}</div>
                  <div class="stat-label">等待上传</div>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon success">
                  <el-icon><Check /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ successTasksCount }}</div>
                  <div class="stat-label">上传成功</div>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon error">
                  <el-icon><Close /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ errorTasksCount }}</div>
                  <div class="stat-label">上传失败</div>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="toolbar-left">
              <el-button-group>
                <el-button
                  :type="filterStatus === 'all' ? 'primary' : ''"
                  @click="filterStatus = 'all'"
                >
                  全部 ({{ uploadStore.tasks.length }})
                </el-button>
                <el-button
                  :type="filterStatus === 'uploading' ? 'primary' : ''"
                  @click="filterStatus = 'uploading'"
                >
                  上传中 ({{ uploadStore.uploadingTasks.length }})
                </el-button>
                <el-button
                  :type="filterStatus === 'waiting' ? 'primary' : ''"
                  @click="filterStatus = 'waiting'"
                >
                  等待中 ({{ waitingTasksCount }})
                </el-button>
                <el-button
                  :type="filterStatus === 'completed' ? 'primary' : ''"
                  @click="filterStatus = 'completed'"
                >
                  已完成 ({{ uploadStore.completedTasks.length }})
                </el-button>
              </el-button-group>
            </div>
            <div class="toolbar-right">
              <el-button type="primary" @click="handleUploadClick">
                <el-icon><Upload /></el-icon>
                上传文件
              </el-button>
              <el-button
                v-if="uploadStore.completedTasks.length > 0"
                @click="uploadStore.clearCompletedTasks"
              >
                清空已完成
              </el-button>
              <el-button
                type="danger"
                @click="handleClearAll"
              >
                清空全部
              </el-button>
            </div>
          </div>

          <!-- 任务列表 -->
          <div class="upload-list">
            <el-card
              v-for="task in filteredTasks"
              :key="task.id"
              class="upload-task-card"
              :class="[`status-${task.status}`]"
            >
              <div class="task-content">
                <!-- 文件信息 -->
                <div class="task-file-info">
                  <div class="file-icon">
                    <el-icon :size="32">
                      <Document />
                    </el-icon>
                  </div>
                  <div class="file-details">
                    <div class="file-name" :title="task.fileName">
                      {{ task.fileName }}
                    </div>
                    <div class="file-meta">
                      <span>{{ uploadStore.formatFileSize(task.fileSize) }}</span>
                      <el-divider direction="vertical" />
                      <span>{{ formatTaskStatus(task.status) }}</span>
                      <el-divider direction="vertical" />
                      <span>{{ formatTime(task.startTime) }}</span>
                    </div>
                  </div>
                </div>

                <!-- 进度信息 -->
                <div class="task-progress">
                  <div class="progress-header">
                    <span class="progress-text">{{ task.progress }}%</span>
                    <span v-if="task.speed > 0" class="upload-speed">
                      {{ uploadStore.formatSpeed(task.speed) }}
                    </span>
                    <span v-if="task.remainingTime > 0" class="remaining-time">
                      剩余 {{ uploadStore.formatTime(task.remainingTime) }}
                    </span>
                  </div>
                  <el-progress
                    :percentage="task.progress"
                    :status="getProgressStatus(task.status)"
                    :stroke-width="8"
                    :show-text="false"
                  />
                  <div v-if="task.status === UploadStatus.ERROR" class="error-message">
                    {{ task.errorMessage || '上传失败' }}
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="task-actions">
                  <el-button
                    v-if="task.status === UploadStatus.UPLOADING"
                    size="small"
                    type="danger"
                    @click="uploadStore.cancelTask(task.id)"
                  >
                    取消
                  </el-button>
                  <el-button
                    v-else-if="task.status === UploadStatus.ERROR"
                    size="small"
                    type="primary"
                    @click="handleRetry(task.id)"
                  >
                    重试
                  </el-button>
                  <el-button
                    v-if="task.status === UploadStatus.SUCCESS || task.status === UploadStatus.ERROR || task.status === UploadStatus.CANCELED"
                    size="small"
                    @click="uploadStore.removeTask(task.id)"
                  >
                    移除
                  </el-button>
                </div>
              </div>
            </el-card>

            <!-- 空状态 -->
            <el-empty
              v-if="filteredTasks.length === 0"
              :description="getEmptyDescription()"
              :image-size="120"
            />
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 文件选择器(隐藏) -->
    <input
      ref="fileInputRef"
      type="file"
      multiple
      style="display: none"
      @change="handleFileSelect"
    />

    <!-- 个人信息对话框 -->
    <UserProfileDialog v-model="showProfileDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useUploadStore, UploadStatus } from '@/stores/upload'
import { fileUploader } from '@/utils/upload'
import UserProfileDialog from '@/components/UserProfileDialog.vue'
import {
  User,
  ArrowDown,
  Folder,
  Share,
  Delete,
  Upload,
  Loading,
  Clock,
  Check,
  Close,
  Document
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const uploadStore = useUploadStore()

// 响应式数据
const showProfileDialog = ref(false)
const fileInputRef = ref<HTMLInputElement>()
const filterStatus = ref<'all' | 'uploading' | 'waiting' | 'completed'>('all')

// 计算属性
const waitingTasksCount = computed(() =>
  uploadStore.tasks.filter(task => task.status === UploadStatus.WAITING).length
)

const successTasksCount = computed(() =>
  uploadStore.tasks.filter(task => task.status === UploadStatus.SUCCESS).length
)

const errorTasksCount = computed(() =>
  uploadStore.tasks.filter(task => task.status === UploadStatus.ERROR).length
)

const filteredTasks = computed(() => {
  switch (filterStatus.value) {
    case 'uploading':
      return uploadStore.uploadingTasks
    case 'waiting':
      return uploadStore.tasks.filter(task => task.status === UploadStatus.WAITING)
    case 'completed':
      return uploadStore.completedTasks
    default:
      return uploadStore.tasks
  }
})

// 处理用户菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      showProfileDialog.value = true
      break
    case 'logout':
      userStore.logout()
      break
  }
}

// 处理上传按钮点击
const handleUploadClick = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (!files || files.length === 0) return

  // 验证文件
  const validFiles: File[] = []
  for (const file of Array.from(files)) {
    const validation = fileUploader.validateFile(file)
    if (validation.valid) {
      validFiles.push(file)
    } else {
      ElMessage.warning(`${file.name}: ${validation.message}`)
    }
  }

  if (validFiles.length === 0) {
    ElMessage.warning('没有有效的文件可以上传')
    return
  }

  try {
    // 开始上传 (默认上传到根目录)
    await fileUploader.uploadFiles(validFiles, 0)
    ElMessage.success(`已添加 ${validFiles.length} 个文件到上传队列`)
  } catch (error: any) {
    ElMessage.error(error.message || '上传失败')
  } finally {
    // 清空文件选择器
    target.value = ''
  }
}

// 重试上传
const handleRetry = (taskId: string) => {
  uploadStore.retryTask(taskId)
  ElMessage.info('重新开始上传')
}

// 清空所有任务
const handleClearAll = async () => {
  if (uploadStore.isUploading) {
    try {
      await ElMessageBox.confirm(
        '当前有文件正在上传，确定要取消所有上传任务吗？',
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      uploadStore.clearAllTasks()
      ElMessage.success('已取消所有上传任务')
    } catch {
      // 用户取消操作
    }
  } else {
    uploadStore.clearAllTasks()
    ElMessage.success('已清空所有任务')
  }
}

// 获取进度条状态
const getProgressStatus = (status: UploadStatus) => {
  switch (status) {
    case UploadStatus.SUCCESS:
      return 'success'
    case UploadStatus.ERROR:
      return 'exception'
    default:
      return undefined
  }
}

// 格式化任务状态
const formatTaskStatus = (status: UploadStatus): string => {
  switch (status) {
    case UploadStatus.WAITING:
      return '等待上传'
    case UploadStatus.UPLOADING:
      return '上传中'
    case UploadStatus.SUCCESS:
      return '上传成功'
    case UploadStatus.ERROR:
      return '上传失败'
    case UploadStatus.CANCELED:
      return '已取消'
    default:
      return '未知状态'
  }
}

// 格式化时间
const formatTime = (timestamp?: number): string => {
  if (!timestamp) return '未开始'
  return new Date(timestamp).toLocaleString()
}

// 获取空状态描述
const getEmptyDescription = (): string => {
  switch (filterStatus.value) {
    case 'uploading':
      return '暂无正在上传的文件'
    case 'waiting':
      return '暂无等待上传的文件'
    case 'completed':
      return '暂无已完成的上传任务'
    default:
      return '暂无上传任务，点击上传文件开始'
  }
}

// 初始化
onMounted(() => {
  // 页面加载时如果有上传任务，自动显示
})
</script>

<style scoped>
.upload-list-container {
  height: 100vh;
  width: 100vw;
  background: #f8f9fa;
}

.el-container {
  height: 100%;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.sidebar {
  background-color: #f5f5f5;
  border-right: 1px solid #e6e6e6;
}

.main-content {
  background: #f8f9fa;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.page-title h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.page-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  padding: 20px;
}

.stat-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.uploading {
  background: #e3f2fd;
  color: #1976d2;
}

.stat-icon.waiting {
  background: #fff3e0;
  color: #f57c00;
}

.stat-icon.success {
  background: #e8f5e8;
  color: #4caf50;
}

.stat-icon.error {
  background: #ffebee;
  color: #f44336;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-card {
  margin: 0 20px 20px 20px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.total-progress-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-title {
  font-weight: 500;
  color: #333;
}

.progress-percentage {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  margin: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upload-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.upload-task-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.upload-task-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.upload-task-card.status-uploading {
  border-left: 4px solid #409eff;
}

.upload-task-card.status-success {
  border-left: 4px solid #67c23a;
}

.upload-task-card.status-error {
  border-left: 4px solid #f56c6c;
}

.upload-task-card.status-waiting {
  border-left: 4px solid #e6a23c;
}

.upload-task-card.status-canceled {
  border-left: 4px solid #909399;
}

.task-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.task-file-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.file-icon {
  color: #409eff;
  flex-shrink: 0;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.file-meta {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
}

.task-progress {
  flex: 1.5;
  min-width: 200px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
}

.upload-speed {
  color: #409eff;
  font-weight: 500;
}

.remaining-time {
  color: #909399;
}

.error-message {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}

.task-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}
</style>